/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> book; // inorder 值与下标的映射关系

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, int left1, int right1, int left2, int right2) {
        if (left1 > right1 || left2 > right2) return nullptr;

        TreeNode* root = new TreeNode(preorder[left1]);
        int inorder_root_index = book[preorder[left1]];
        int left_num = inorder_root_index - left2;
        int right_num = right2 - inorder_root_index;

        root->left = buildTree(preorder, inorder, left1 + 1, left1 + left_num, left2, inorder_root_index - 1);
        root->right = buildTree(preorder, inorder, left1 + left_num + 1, left1 + left_num + right_num, inorder_root_index + 1, right2);
        return root;

    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for (int i = 0; i < n; i++) {
            book[inorder[i]] = i;
        }

        return buildTree(preorder, inorder, 0, n - 1, 0, n - 1);
    }
};
